using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using iver.Entity;
using DBEntity;
using NPOI.HSSF.UserModel;
//using NPOI.HPSF;
//using NPOI.POIFS.FileSystem;
//using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace iver.Controllers
{
    public class sfLogController : ApiController
    {
        /// <summary>
        /// 得到列表
        /// </summary>
        [HttpPost]
        public ResResult sfLogList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.apSFLog
                        orderby u.id descending
                        select u);
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }


        public class ReqsfLogList : ReqList
        {
            public string userGroup { get; set; }
            public string userName { get; set; }
            public string screenshot { get; set; }
            public string detail { get; set; }
            public string reply { get; set; }
            public Nullable<int> dealCount { get; set; }
            public Nullable<bool> isDeal { get; set; }
            public string createTime { get; set; }
            public string dealTime { get; set; }
            public string updateTime { get; set; }
            public string remark { get; set; }
            public string dealName { get; set; }
            public string createName { get; set; }
            public Nullable<bool> isSend { get; set; }

        }
        /// <summary>
        /// 得到列表通过条件
        /// </summary>
        [HttpPost]
        public ResResult sfLogListByQuery([FromBody]ReqsfLogList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }

            DateTime? b_createTime = null;
            DateTime? e_createTime = null;
            if (req.createTime != null)
            {
                string[] temp = req.createTime.Split(',');
                DateTime bt = Convert.ToDateTime(temp[0]);
                DateTime et = Convert.ToDateTime(temp[1]);
                b_createTime = new DateTime(bt.Year, bt.Month, bt.Day, 0, 0, 0);
                e_createTime = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);
            }


            DateTime? b_dealTime = null;
            DateTime? e_dealTime = null;
            if (req.dealTime != null)
            {
                string[] temp = req.dealTime.Split(',');
                DateTime bt = Convert.ToDateTime(temp[0]);
                DateTime et = Convert.ToDateTime(temp[1]);
                b_dealTime = new DateTime(bt.Year, bt.Month, bt.Day, 0, 0, 0);
                e_dealTime = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);
            }


            DateTime? b_updateTime = null;
            DateTime? e_updateTime = null;
            if (req.updateTime != null)
            {
                string[] temp = req.updateTime.Split(',');
                DateTime bt = Convert.ToDateTime(temp[0]);
                DateTime et = Convert.ToDateTime(temp[1]);
                b_updateTime = new DateTime(bt.Year, bt.Month, bt.Day, 0, 0, 0);
                e_updateTime = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);
            }

            iverDB db = new iverDB();
            var list = (from u in db.apSFLog

                        orderby u.id descending
                        where
                            1 == 1
                        && (req.userGroup == null ? 1 == 1 : u.userGroup.Contains(req.userGroup))
                        && (req.userName == null ? 1 == 1 : u.userName.Contains(req.userName))
                        && (req.screenshot == null ? 1 == 1 : u.screenshot.Contains(req.screenshot))
                        && (req.detail == null ? 1 == 1 : u.detail.Contains(req.detail))
                        && (req.reply == null ? 1 == 1 : u.reply.Contains(req.reply))
                        && (req.dealCount == null ? 1 == 1 : u.dealCount == req.dealCount)
                        && (req.isDeal == null ? 1 == 1 : u.isDeal == req.isDeal)
                        && (req.createTime == null ? 1 == 1 : (u.createTime >= b_createTime && u.createTime <= e_createTime))
                        && (req.dealTime == null ? 1 == 1 : (u.dealTime >= b_dealTime && u.dealTime <= e_dealTime))
                        && (req.updateTime == null ? 1 == 1 : (u.updateTime >= b_updateTime && u.updateTime <= e_updateTime))
                        && (req.remark == null ? 1 == 1 : u.remark.Contains(req.remark))
                        && (req.dealName == null ? 1 == 1 : u.dealName.Contains(req.dealName))
                        && (req.createName == null ? 1 == 1 : u.createName.Contains(req.createName))
                        && (req.isSend == null ? 1 == 1 : u.isSend == req.isSend)

                        select new
                        {
                            u.id,
                            u.userGroup,
                            u.userName,
                            u.screenshot,
                            u.detail,
                            u.reply,
                            u.dealCount,
                            u.isDeal,
                            u.createTime,
                            u.dealTime,
                            u.updateTime,
                            u.remark,
                            u.dealName,
                            u.createName,
                            u.isSend,

                        });
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost]
        public ResResult sfLogAdd([FromBody]apSFLog req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            db.apSFLog.Add(req);

            DateTime now = DateTime.Now;
            req.reply = "无";
            req.dealCount = 1;
            req.isDeal = false;
            req.createTime = now;
            req.dealTime = now;
            req.updateTime = now;
            req.remark = "";
            req.dealName = authInfo.trueName;
            req.createName = authInfo.trueName;
            req.isSend = false;
            db.SaveChanges();

            Help.Log(authInfo, req.id.ToString());
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    id = req.id,
                },
            };
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [HttpPost]
        public ResResult sfLogEdit([FromBody]apSFLog req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            apSFLog model = db.apSFLog.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            model.userGroup = req.userGroup == null ? model.userGroup : req.userGroup;
            model.userName = req.userName == null ? model.userName : req.userName;
            model.screenshot = req.screenshot == null ? model.screenshot : req.screenshot;
            model.detail = req.detail == null ? model.detail : req.detail;
            if (req.isDeal == true && model.reply == "无")
            {
                model.reply = "已处理";
            }
            else
            {
                model.reply = req.reply == null ? model.reply : req.reply;
            }
            model.dealCount = req.dealCount == null ? model.dealCount : req.dealCount;
            model.isDeal = req.isDeal == null ? model.isDeal : req.isDeal;
            //model.createTime = req.createTime == null ? model.createTime : req.createTime;
            model.dealTime = req.dealTime == null ? model.dealTime : req.dealTime;
            model.updateTime = DateTime.Now;
            model.remark = req.remark == null ? model.remark : req.remark;
            model.dealName = authInfo.trueName;
            //model.createName = req.createName == null ? model.createName : req.createName;
            model.isSend = req.isSend == null ? model.isSend : req.isSend;
            int result = db.SaveChanges();
            Help.Log(authInfo, req.id.ToString());
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        public class ReqsfLogMulti
        {
            public List<int> idList { get; set; }
            public Nullable<bool> isBool { get; set; }
            public string boolType { get; set; }
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult sfLogEditMulti([FromBody]ReqsfLogMulti req)
        {
            //System.Threading.Thread.Sleep(3000);
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            var list = from u in db.apSFLog
                       where req.idList.Contains(u.id)
                       select u;

            foreach (var item in list)   //重新赋值
            {
                if(req.boolType == "isDeal")
                {
                    item.isDeal = req.isBool;
                }
                else
                {
                    item.isSend = req.isBool;
                }
                if (req.isBool == true && item.reply == "无")
                {
                    item.reply = "已处理";
                }
            }
            int result = db.SaveChanges();
            Help.Log(authInfo, Newtonsoft.Json.JsonConvert.SerializeObject(req));
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public ResResult sfLogDel([FromBody]ReqID<List<int>> req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = db.apSFLog.Where(u => req.id.Contains(u.id));
            int delCount = list.Count();
            if (delCount == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            db.apSFLog.RemoveRange(list);
            db.SaveChanges();
            Help.Log(authInfo, Newtonsoft.Json.JsonConvert.SerializeObject(req.id));
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessDel,
                result = new
                {
                    delCount,
                },
            };
        }

        /// <summary>
        /// excel导入参数
        /// </summary>
        public class ReqImport
        {
            public string label { get; set; }
            public string value { get; set; }
            public string type { get; set; }
        }
        /// <summary>
        /// excel导入
        /// </summary>
        [HttpPost]
        public ResResult importExcel()
        {

            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            if (System.Web.HttpContext.Current.Request["jsonStr"] == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "无导入参数",

                };
            }
            IWorkbook workbook;
            string fileExt = System.IO.Path.GetExtension(System.Web.HttpContext.Current.Request.Files[0].FileName);
            if (!(fileExt.ToLower() == ".xls" || fileExt.ToLower() == ".xlsx"))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "文件格式错误",

                };
            }

            string jsonStr = System.Web.HttpContext.Current.Request["jsonStr"];
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<ReqImport> mylist = js.Deserialize<List<ReqImport>>(jsonStr);
            List<ReqImport> oldlist = new List<ReqImport>();

            oldlist.Add(new ReqImport()
            {
                value = "userGroup",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "userName",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "screenshot",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "detail",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "reply",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "dealCount",
                type = "int",
            });
            oldlist.Add(new ReqImport()
            {
                value = "isDeal",
                type = "bit",
            });
            oldlist.Add(new ReqImport()
            {
                value = "createTime",
                type = "datetime",
            });
            oldlist.Add(new ReqImport()
            {
                value = "dealTime",
                type = "datetime",
            });
            oldlist.Add(new ReqImport()
            {
                value = "updateTime",
                type = "datetime",
            });
            oldlist.Add(new ReqImport()
            {
                value = "remark",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "dealName",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "createName",
                type = "varchar",
            });
            oldlist.Add(new ReqImport()
            {
                value = "isSend",
                type = "bit",
            });
            List<ReqImport> dbList = new List<ReqImport>();
            for (int i = 0; i < oldlist.Count; i++)
            {
                for (int j = 0; j < mylist.Count; j++)
                {
                    if (mylist[j].value == oldlist[i].value)
                    {

                        dbList.Add(new ReqImport()
                        {
                            label = mylist[j].label,
                            value = oldlist[i].value,
                            type = oldlist[i].type,
                        });
                        break;
                    }
                }
            }

            if (fileExt == ".xls")
            {
                workbook = new HSSFWorkbook(System.Web.HttpContext.Current.Request.Files[0].InputStream);
            }
            else
            {
                workbook = new XSSFWorkbook(System.Web.HttpContext.Current.Request.Files[0].InputStream);
            }
            ISheet _sheet = workbook.GetSheetAt(0);
            List<ReqImport> flist = new List<ReqImport>();
            bool flag = false;
            for (int i = 0; i < _sheet.GetRow(0).Cells.Count; i++)
            {
                bool flaghas = false;
                for (int j = 0; j < dbList.Count; j++)
                {
                    if (dbList[j].label == _sheet.GetRow(0).Cells[i].ToString())
                    {
                        flaghas = true;
                        flist.Add(dbList[j]);
                        break;
                    }
                }
                if (!flaghas)
                {
                    flag = true;
                }
            }
            if (flag)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "导入格式错误",
                };
            }
            ////数组去重
            //for (int i = 0; i < flist.Count; i++)
            //{
            //    List<ReqImport> ll = flist.FindAll(p => p.value == flist[i].value);
            //    if (ll.Count > 1)
            //    {
            //        flist.Remove(ll[0]);
            //    }
            //}
            List<ReqImport> finalList = flist;
            List<apSFLog> list = new List<apSFLog>();
            for (int i = _sheet.LastRowNum; i > 0; i--)
            {
                apSFLog model = new apSFLog();
                IRow row = _sheet.GetRow(i);
                IRow typeRow = _sheet.GetRow(0);
                for (int j = 0; j < row.LastCellNum; j++)
                {
                    List<ReqImport> rs = finalList.FindAll(p => p.label == typeRow.Cells[j].ToString());
                    string cellVal = row.Cells[j].ToString();
                    switch (rs[0].type)
                    {
                        case "int":
                            int int_v;
                            if (int.TryParse(cellVal, out int_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, int_v);
                            }
                            break;
                        case "datetime":
                            DateTime DateTime_v;
                            if (DateTime.TryParse(cellVal, out DateTime_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, DateTime_v);
                            }
                            break;
                        case "bit":
                            bool bool_v;
                            if (bool.TryParse(cellVal, out bool_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, bool_v);
                            }
                            break;
                        case "decimal":
                            decimal decimal_v;
                            if (decimal.TryParse(cellVal, out decimal_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, decimal_v);
                            }
                            break;
                        default:
                            model.GetType().GetProperty(rs[0].value).SetValue(model, cellVal);
                            break;
                    }
                }
                list.Add(model);
            }
            iverDB db = new iverDB();
            db.apSFLog.AddRange(list);
            int count = db.SaveChanges();
            Help.Log(authInfo, count.ToString());

            return new ResResult
            {
                success = true,
                result = finalList,
            };

        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResResult uploadImg()
        {
            Entity.AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            return Help.uploadfile("sfLog", 3);
        }

    }
}
